<template>
  <div class="organization">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span style="font-size: 18px; font-weight: bold">组织管理</span>
      </div>
      <!-- 查询表单 -->
      <el-row>
        <el-col :span="24">
          <el-form inline class="query-form">
            <el-form-item label="组织编码">
              <el-input
                v-model="query.organizationId"
                placeholder="请输入组织编码"
              ></el-input>
            </el-form-item>
            <el-form-item label="公司名称">
              <el-input
                v-model="query.companyName"
                placeholder="请输入公司名称"
              ></el-input>
            </el-form-item>
            <el-form-item label="公司位置">
              <el-input
                v-model="query.companyAddress"
                placeholder="请输入公司位置"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="fetchData">查询</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <!-- 操作按钮 -->
      <el-row>
        <el-col :span="24">
          <el-button type="success" @click="handleAdd" class="add-button"
            >新增组织</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格展示 -->
      <el-row>
        <el-col :span="24">
          <el-table
            :data="tableData"
            border
            style="width: 100%"
            class="org-table"
          >
            <el-table-column
              prop="organizationId"
              label="组织编码"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="companyName"
              label="公司名称"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="companyAddress"
              label="公司位置"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="companyPhone"
              label="公司电话"
              align="center"
            ></el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button type="text" @click="handleEdit(scope.row)"
                  >编辑</el-button
                >
                <el-button type="text" @click="handleDelete(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <!-- 分页组件 -->
      <el-row>
        <el-col :span="24">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </el-col>
      </el-row>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
    >
      <el-form
        ref="orgForm"
        :model="orgForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="组织编码">
          <el-input
            v-model="orgForm.organizationId"
            placeholder="请输入组织编码"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="公司名称" prop="companyName">
          <el-input
            v-model="orgForm.companyName"
            placeholder="请输入公司名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="公司位置" prop="companyAddress">
          <el-input
            v-model="orgForm.companyAddress"
            placeholder="请输入公司位置"
          ></el-input>
        </el-form-item>
        <el-form-item label="公司电话" prop="companyPhone">
          <el-input
            v-model="orgForm.companyPhone"
            placeholder="请输入公司电话"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveOrganization">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  organizationsCreate,
  organizationsDelete,
  organizationsEdit,
  organizationsPageQuey,
} from "@/api/organizationsApi";

export default {
  name: "AdminOrganization",
  data() {
    return {
      query: {
        organizationId: "",
        companyName: "",
        companyAddress: "",
      },
      tableData: [],
      currentPage: 1,
      pageSize: 5,
      total: 0,
      dialogVisible: false,
      dialogTitle: "新增组织",
      orgForm: {
        organizationId: "",
        companyName: "",
        companyAddress: "",
        companyPhone: "",
      },
      currentOrg: null,
      rules: {
        companyName: [
          { required: true, message: "请输入公司名称", trigger: "blur" },
        ],
        companyAddress: [
          { required: true, message: "请输入公司位置", trigger: "blur" },
        ],
        companyPhone: [
          { required: true, message: "请输入公司电话", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "请输入有效的手机号码",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    // 获取组织列表
    fetchData() {
      const params = {
        pageRequestDto: {
          page: this.currentPage,
          size: this.pageSize,
        },
        query: {
          organizationId: this.query.organizationId, // 添加组织编码查询条件
          companyName: this.query.companyName, // 添加公司名称查询条件
          companyAddress: this.query.companyAddress, // 添加公司位置查询条件
        },
      };

      organizationsPageQuey(params)
        .then((res) => {
          this.tableData = res.data.records; // 假设后端返回的组织数据在 `records` 字段
          this.total = res.data.total; // 假设后端返回的总记录数在 `total` 字段
        })
        .catch((error) => {
          console.error("获取组织列表失败", error);
          this.$message.error("获取组织列表失败");
        });
    },
    // 重置查询条件
    resetQuery() {
      this.query.organizationId = "";
      this.query.companyName = "";
      this.query.companyAddress = "";
      this.fetchData();
    },
    // 新增组织
    handleAdd() {
      this.dialogTitle = "新增组织";
      this.orgForm = {
        organizationId: "",
        companyName: "",
        companyAddress: "",
        companyPhone: "",
      };
      this.dialogVisible = true;
    },
    // 编辑组织
    handleEdit(row) {
      this.dialogTitle = "编辑组织";
      this.currentOrg = row;
      this.orgForm = { ...row };
      this.dialogVisible = true;
    },
    // 删除组织
    handleDelete(row) {
      this.$confirm(`确定要删除组织 ${row.organizationId} 吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          organizationsDelete(row.organizationId)
            .then(() => {
              this.$message.success("删除成功");
              this.fetchData(); // 刷新列表
            })
            .catch((error) => {
              console.error("删除组织失败", error);
              this.$message.error("删除组织失败");
            });
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    // 保存组织（新增或编辑）
    saveOrganization() {
      this.$refs.orgForm.validate((valid) => {
        if (valid) {
          if (this.dialogTitle === "新增组织") {
            organizationsCreate(this.orgForm)
              .then(() => {
                this.$message.success("新增成功");
                this.fetchData(); // 刷新列表
              })
              .catch((error) => {
                console.error("新增组织失败", error);
                this.$message.error("新增组织失败");
              });
          } else {
            organizationsEdit(this.currentOrg.organizationId, this.orgForm)
              .then(() => {
                this.$message.success("编辑成功");
                this.fetchData(); // 刷新列表
              })
              .catch((error) => {
                console.error("编辑组织失败", error);
                this.$message.error("编辑组织失败");
              });
          }
          this.dialogVisible = false;
        } else {
          this.$message.error("表单验证失败，请检查输入信息");
          return false;
        }
      });
    },

    // 分页大小改变
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.fetchData();
    },
    // 当前页码改变
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchData();
    },
    // 对话框关闭
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
  },
  mounted() {
    this.fetchData();
  },
};
</script>

<style scoped>
.organization {
  padding: 20px;
}
.box-card {
  margin-bottom: 20px;
}
.query-form {
  margin-bottom: 20px;
}
.org-table {
  margin-top: 20px;
}
.add-button {
  float: left; /* 将按钮置于左侧 */
}
</style>